package com.mojo.concurrent.concurrent_02_lock;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock公平和非公平模式使用示例
 *
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
public class ReentrantLock02 {
    //公平锁或非公平锁
    static ReentrantLock lock = new ReentrantLock(true);

    public static void main(String[] args) {
        MyThread t1 = new MyThread(lock, "t1");
        MyThread t2 = new MyThread(lock, "t2");
        MyThread t3 = new MyThread(lock, "t3");
        //非公平锁，执行顺序不一定为start调用顺序
        /*
            name===>t1
            name===>t3
            name===>t2
         */
        t1.start();
        t3.start();
        t2.start();
    }
}

class MyThread extends Thread {
    ReentrantLock lock;
    String name;

    public MyThread(ReentrantLock lock, String name) {
        this.lock = lock;
        this.name = name;
    }

    @Override
    public void run() {
        lock.lock();
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
        System.out.println("name===>" + name);
    }
}
